<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          clearable
          @input="changeValue"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="deptTree"
          :data="depts"
          :props="defaultProps"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          node-key="id"
          @current-change="selectNode"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'add-employee'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <!-- <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button> -->
          <el-button size="mini" @click="showExcelDialog=true">excel导入</el-button>
          <importExcel :show-excel-dialog.sync="showExcelDialog" @uploadSuccess="getEmployee" />
          <el-button size="mini" @click="exportEmployee">excel导出</el-button>

        </el-row>
        <!-- 表格组件 sortable排序-->
        <el-table :data="list">
          <el-table-column prop="staffPhoto" label="头像" align="center">
            <template v-slot="{row}">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span v-else :size="30" class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable sort-by="index" />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="{row}">
              <span v-if="row.formOfEmployment===1">正式</span>
              <span v-else-if="row.formOfEmployment===2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable="time" />
          <el-table-column label="操作" width="289px" align="center">
            <template v-slot="{row}">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <!-- <el-button size="mini" type="text" @click="btnRole(row.id)">角色</el-button> -->
              <el-button size="mini" type="text" @click="btnRole(row.id)">角色</el-button>
              <el-dialog :visible.sync="showRoleDialog" title="分配角色">
                <el-checkbox-group v-model="roleIds">
                  <el-checkbox
                    v-for="item in roleList"
                    :key="item.id"
                    :label="item.id"
                  >{{ item.name }}</el-checkbox>
                </el-checkbox-group>
                <!-- 给弹出层加底部按钮 -->
                <!--<el-row slot="footer" type="flex" justify="center">
                  <el-button size="mini" type="primary" @click="btnRoleOK">确定</el-button>
                  <el-button size="mini" @click="showRoleDialog=false">取消</el-button>
                </el-row> -->
                <el-row slot="footer" type="flex" justify="center">
                  <el-col :span="6">
                    <el-button type="primary" size="mini" @click="btnRoleOK">确定</el-button>
                    <el-button size="mini" @click="showRoleDialog = false">取消</el-button>
                  </el-col>
                </el-row>
              </el-dialog>
              <el-popconfirm title="确认删除该行数据吗？" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- <el-table>
          <el-table-column align="center" label="头像" />
          <el-table-column label="姓名" />
          <el-table-column label="手机号" sortable />
          <el-table-column label="工号" sortable />
          <el-table-column label="聘用形式" />
          <el-table-column label="部门" />
          <el-table-column label="入职时间" sortable />
          <el-table-column label="操作" width="280px">
            <template>
              <el-button size="mini" type="text">查看</el-button>
              <el-button size="mini" type="text">角色</el-button>
              <el-button size="mini" type="text">删除</el-button>
            </template>
          </el-table-column>
        </el-table> -->
        <!-- 分页 并绑定分页参数-->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total,prev, pager, next"
            :total="total"
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            @current-change="changePage"
          />
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import { debounce } from 'lodash'
import { transListToTreeData } from '@/utils'
import { getDepartment } from '@/api/department'
import { assignRole, delEmployee, exportEmployee, getEmployee, getEmployeeDetail, getEnableRoleList } from '@/api/employee'
import FileSaver from 'file-saver'
import importExcel from './components/import-excel.vue'
export default {
  name: 'Employee',
  components: {
    importExcel
  },
  data() {
    return {
      currentusreId: null,
      currentUserId: null, // 用来记录当前点击用户的id
      showRoleDialog: false,
      roleList: [], // 接受角色列表
      roleIds: [], // 用来双向绑定数据
      depts: [], // 部门数据
      list: [],
      showExcelDialog: false, // 控制excel的弹层显示和隐藏
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      queryParams: {
        page: 1, // 当前页码
        pagesize: 10,
        keyword: '', // 模糊字段
        departmentId: null
      },
      total: 0 // 记录员工总数
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    // 点击角色按钮弹出层
    // async btnRole() {
    //   this.showRoleDialog = true
    //   this.roleList = await getEnableRoleList()
    // },
    async btnRole(id) {
      this.roleList = await getEnableRoleList()
      // 记录当前点击的id 因为后边 确定取消要存取给对应的用户
      this.currentUserId = id
      this.currentusreId = id
      const { roleIds } = await getEmployeeDetail(id)
      this.roleIds = roleIds // 获取可用角色列表
      this.showRoleDialog = true // 调整顺序 最后显示弹层
    },
    // 点击角色的确定
    async btnRoleOK() {
      await assignRole({
        id: this.currentUserId, // 当前用户的id
        roleIds: this.roleIds // 当前用户的最新角色列表
      })
      this.$message.success('分配用户角色成功')
      this.showRoleDialog = false
    },
    async getDepartment() {
      // 获取全部的部门数据 树形数据
      this.depts = transListToTreeData(await getDepartment(), 0)
      this.queryParams.departmentId = this.depts[0].id
      this.$nextTick(() => {
        // 默认的是根节点的部门选中 前提是设置node-key 属性为id
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
      })
      // 调用获取员工列表的方法
      this.getEmployee()
    },
    async getEmployee() {
      const { rows, total } = await getEmployee(this.queryParams)
      this.list = rows
      this.total = total
    },
    selectNode(data) {
      this.queryParams.departmentId = data.id
      this.queryParams.page = 1// 设置第一页
      // 重新记录了员工参数
      this.getEmployee()
    },
    // 切换页码
    changePage(newPage) {
      this.queryParams.page = newPage // 把变更的页码赋给查询页码
      this.getEmployee() // 获取员工数据
    },
    async exportEmployee() {
      const result = await exportEmployee() // 1.导出全部员工接口
      FileSaver.saveAs(result, '员工Info表.xlsx') // 2.用npm的文件保存包 把blob文件下载到本地
    },
    // created() {
    //   delEmployee()
    // },
    // 删除员工方法
    async confirmDel(id) {
      await delEmployee(id)
      if (this.list.length === 1 && this.queryParams.page > 1) this.queryParams.page--
      this.getEmployee()
      this.$message.success('删除员工成功')
    },
    // 值改变查询数据
    changeValue: debounce(function() {
      // 使用lodash的防抖函数:debounce(function() {},300)
      this.queryParams.page = 1 // keyword值改变 重置页码
      this.getEmployee()
    }, 500)
    // changeValue() {
    //   // 支持防抖 设置一定时间间隔 只执行最后一次
    //   clearTimeout(this.timer)// 清理上一次定时器
    //   this.timer = setTimeout(() => {
    //     this.queryParams.page = 1
    //     this.getEmployee()
    //   }, 500)
    // }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
